Component({
  properties: {
    signList: {
      type: Array,
      value: []
    }
  },
  data: {
    currentYear: null,
    currentMonth: null,
    year: 0,
    month: 0,
    days: [],
    blankDays: [],
    nextBlankDays: [],
    weekDays: ['日', '一', '二', '三', '四', '五', '六']
  },
  observers: {
    'signList': function () {
      this.initCalendar();
    }
  },
  lifetimes: {
    attached() {
      const date = new Date();
      const year = date.getFullYear();
      const month = date.getMonth() + 1;
      this.setData({ year, month, currentYear: year, currentMonth: month }, this.initCalendar);
    }
  },
  methods: {
    pad(n) {
      return n < 10 ? '0' + n : '' + n;
    },
    initCalendar() {
      const { year, month, signList } = this.data;
      let firstDay = new Date(year, month - 1, 1).getDay();
      firstDay = firstDay === 0 ? 7 : firstDay;
      const daysCount = new Date(year, month, 0).getDate();

      const today = new Date();
      const todayStr = `${today.getFullYear()}-${this.pad(today.getMonth() + 1)}-${this.pad(today.getDate())}`;

      const days = Array.from({ length: daysCount }, (_, i) => {
        const day = i + 1;
        const dateStr = `${year}-${this.pad(month)}-${this.pad(day)}`;
        return {
          day,
          isToday: dateStr === todayStr,
          isSigned: signList.includes(dateStr)
        };
      });

      const prevMonthLastDay = new Date(year, month - 1, 0).getDate();
      const blankDays = Array.from({ length: firstDay }, (_, i) => prevMonthLastDay - firstDay + i + 1);
      const totalCells = blankDays.length + days.length;
      const remaining = 42 - totalCells;
      const nextBlankDays = Array.from({ length: remaining }, (_, i) => i + 1);

      this.setData({ days, blankDays, nextBlankDays });
    },
    handleSign() {
      const today = new Date();
      const dateStr = `${today.getFullYear()}-${this.pad(today.getMonth() + 1)}-${this.pad(today.getDate())}`;
      if (!this.data.signList.includes(dateStr)) {
        const newSignList = [...this.data.signList, dateStr];
        this.setData({ signList: newSignList }, () => {
          this.initCalendar();
        });
      }
      this.triggerEvent('onsign', { date: dateStr });
    },
    decreaseMonth() {
      let { year, month } = this.data;
      if (month === 1) {
        year -= 1;
        month = 12;
      } else {
        month -= 1;
      }
      this.setData({ year, month }, this.initCalendar);
    },
    increaseMonth() {
      let { year, month } = this.data;
      if (month === 12) {
        year += 1;
        month = 1;
      } else {
        month += 1;
      }
      this.setData({ year, month }, this.initCalendar);
    }
  }
});
